package com.gilight.base.service.impl;

import com.alibaba.fastjson.JSON;
import com.gilight.base.base.LoginUserInfo;
import com.gilight.base.base.ParameterException;
import com.gilight.base.common.BzdmConstant;
import com.gilight.base.config.jwt.common.Constant;
import com.gilight.base.config.jwt.util.JwtUtil;
import com.gilight.base.dao.SysPermissionMapper;
import com.gilight.base.model.SysUser;
import com.gilight.base.service.MenuService;
import com.gilight.base.util.ShiroUtil;
import org.apache.commons.collections4.MapUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class MenuServiceImpl implements MenuService {

    @Autowired
    private SysPermissionMapper sysPermissionMapper;

    @Override
    @Cacheable(value = BzdmConstant.REDIS_LOADMENU, sync = true)
    public List<Map<String,Object>> loadMenu(Long id) {
        List<Map<String,Object>> list = sysPermissionMapper.loadMenuByUserId(id,-1L);
        this.addChildren(list,id);
        return list;
    }

    private void addChildren(List<Map<String,Object>> list,Long userId){
        for (Map<String,Object> map:list) {
            List<Map<String,Object>> children = sysPermissionMapper.loadMenuByUserId(userId, MapUtils.getLong(map,"id"));
            map.put("children",children);
        }
    }

    @Override
    public List<Map<String,Object>> loadMenu2(String appKey) {
        SysUser sysUser = ShiroUtil.getJWTUser();
        Long userId = sysUser.getId();
        //查询用户默认的角色id
        List<Long> roleIds = sysPermissionMapper.getUserDefaultRoleByUserId(userId);
        if(roleIds.size()==0 || null == roleIds.get(0)){
            throw new ParameterException("获取用户角色出错请联系管理员");
        }
        List<Map<String,Object>> list = sysPermissionMapper.loadMenuByUserId2(userId,-1L,roleIds.get(0),appKey);
        this.addChildren2(list,userId,roleIds.get(0),appKey);
        return list;
    }

    private void addChildren2(List<Map<String,Object>> list,Long userId,Long roleId,String appKey){
        for (Map<String,Object> map:list) {
            List<Map<String,Object>> children = sysPermissionMapper.loadMenuByUserId2(userId, MapUtils.getLong(map,"id"),roleId,appKey);
            map.put("children",children);
        }
    }

    @Override
    public void saveChangeMenu(Long userId, Long roleId) {
        if (null == userId){
            throw new ParameterException("获取用户id出错");
        }

        if (null == roleId){
            throw new ParameterException("角色id不能为空");
        }

        sysPermissionMapper.updateUserDefaultRole(userId,roleId);
    }

}
